var _leftPart;
var _rightPart;
var categoryList;

function init() {
    _leftPart = $('.left-part');
    _rightPart = $('.right-part');

    mui.ajax($.constant.webRoot() + 'v1/category/tree', {
        dataType: 'json',
        type: 'GET',
        async: false,
        success: function (data) {
            categoryList = data;
        }
    });
}

function initRightPart(list) {
    _rightPart.empty();
    if (!list) {
        return;
    }
    $.each(list, function (i, item) {
        var $contentItemHtml = $('<div class="content-item"></div>');
        $contentItemHtml.append('<img src="' + item.coverPictureUrl + '">');
        $contentItemHtml.append('<div class="title"><span>' + item.name + '</span></div>');
        _rightPart.append($contentItemHtml);
        var url = '../list/index.html?id=' + item.id;
        $contentItemHtml.bind('tap', function () {
            mui.openWindow(url);
        });
    });
}

function initView() {

    if (categoryList) {
        for (var i = 0; i < categoryList.length; i++) {
            var titleItemHtml;
            var titleItem = categoryList[i];
            titleItemHtml = '<div class="title-item" data-index="' + i + '">' + titleItem.name + '</div>';
            _leftPart.append(titleItemHtml);
        }
    }
}

function initListen() {

    var _titleItem = $(".title-item");
    _titleItem.bind('tap', function () {
        $(this).siblings().removeClass("active");
        $(this).addClass("active");

        var index = $(this).data("index");
        var item = categoryList[index];
        if (!item.categoryList || item.categoryList.length === 0) {
            var url = '../list/index.html?id=' + item.id;
            mui.openWindow(url);
        } else {
            initRightPart(item.categoryList);
        }
    });
    mui.trigger(_titleItem[0], 'tap');
}

$(function () {

    init();
    initView();
    initListen();

});



